#include "AddPurchaseDialog.h"

#include <wx/wx.h>
#include <wx/textctrl.h>
#include <wx/button.h>
#include <wx/stattext.h>
#include <wx/sizer.h>
#include <wx/datectrl.h> // 确保包含日期选择器头文件
#include <wx/spinctrl.h>

#include "../book_info.h"

BEGIN_EVENT_TABLE(AddPurchaseDialog, wxDialog)
    EVT_BUTTON(wxID_OK, AddPurchaseDialog::OnOK)
    EVT_BUTTON(wxID_CANCEL, AddPurchaseDialog::OnCancel)
END_EVENT_TABLE()

AddPurchaseDialog::AddPurchaseDialog(wxWindow* parent)
    : wxDialog(parent, wxID_ANY, wxT("添加图书采购信息"), wxDefaultPosition, wxSize(400, 300)) {

    wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL);

    wxFlexGridSizer* fgs = new wxFlexGridSizer(2, 5, 9);

    fgs->Add(new wxStaticText(this, wxID_ANY, wxT("图书ID")), 0, wxALIGN_CENTER_VERTICAL);
    m_bookIdCtrl = new wxTextCtrl(this, wxID_ANY);
    fgs->Add(m_bookIdCtrl, 1, wxEXPAND);

    fgs->Add(new wxStaticText(this, wxID_ANY, wxT("数量")), 0, wxALIGN_CENTER_VERTICAL);
    m_quantityCtrl = new wxSpinCtrl(this, wxID_ANY, wxT("0"), wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 0, 1000, 0);
    fgs->Add(m_quantityCtrl, 1, wxEXPAND);

    fgs->Add(new wxStaticText(this, wxID_ANY, wxT("采购日期")), 0, wxALIGN_CENTER_VERTICAL);
    m_dateCtrl = new wxDatePickerCtrl(this, wxID_ANY, wxDefaultDateTime, wxDefaultPosition, wxDefaultSize, wxDP_DROPDOWN | wxDP_SHOWCENTURY);
    fgs->Add(m_dateCtrl, 1, wxEXPAND);

    fgs->Add(new wxStaticText(this, wxID_ANY, wxT("单价")), 0, wxALIGN_CENTER_VERTICAL);
    m_priceCtrl = new wxTextCtrl(this, wxID_ANY, wxT("0.0"));
    fgs->Add(m_priceCtrl, 1, wxEXPAND);

    vbox->Add(fgs, 1, wxALL | wxEXPAND, 10);

    wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL);
    btnSizer->Add(new wxButton(this, wxID_OK, wxT("确定")), 0, wxALL, 5);
    btnSizer->Add(new wxButton(this, wxID_CANCEL, wxT("取消")), 0, wxALL, 5);

    vbox->Add(btnSizer, 0, wxALIGN_CENTER);

    SetSizer(vbox);
    Centre();
}

PurchaseInfo AddPurchaseDialog::GetPurchaseInfo() const {
    // 获取采购日期并格式化为 time_t
    wxDateTime purchaseDate = m_dateCtrl->GetValue();
    time_t dateTicks = purchaseDate.GetTicks();

    return PurchaseInfo(
        -1, // PurchaseID 设置为 -1 表示自增
        m_bookIdCtrl->GetValue().ToStdString(),
        m_quantityCtrl->GetValue(),
        dateTicks,
        std::stod(m_priceCtrl->GetValue().ToStdString())
    );
}

void AddPurchaseDialog::OnOK(wxCommandEvent& event) {
    EndModal(wxID_OK);
}

void AddPurchaseDialog::OnCancel(wxCommandEvent& event) {
    EndModal(wxID_CANCEL);
}
